<?php /** @noinspection PhpUndefinedFieldInspection */

/**
 * @link https://gitee.com/toshcn/micro-hau
 * @copyright Copyright (c) 2022/4/22 micro-hau
 * @author toshcn <toshcn@foxmail.com>
 */

namespace api\modules\v1\controllers;

use Yii;
use api\controllers\ApiController;
use api\modules\v1\forms\UserLoginForm;
use api\modules\v1\forms\UserRegisterForm;
use yii\web\Request;
/**
 * 账号登录，注册相关控制器
 * Class AccountController
 * @package api\modules\v1\controllers
 */
class AccountController extends ApiController
{
    /**
     * 账号注册
     */
    public function actionRegister()
    {
        $this->validateIsPost();
        $form = new UserRegisterForm();
        // 从post中取出数据，赋值给注册表单对应字段
        if ($form->load(Yii::$app->getRequest()->post(), '') && $form->register()) {
            return Yii::$app->api->success();
        }
        if ($form->hasErrors()) {
            return Yii::$app->api->error(parent::ERROR_CODE_FORM_FIELD_ERROR, $form->getFirstOneError());
        }
        return Yii::$app->api->error(parent::ERROR_CODE_FORM_ERROR, Yii::t('common', 'Account registration failed.'));
    }

    /**
     * @return mixed
     */
    public function actionLogin()
    {
        $this->validateIsPost();
        $form = new UserLoginForm();
        // 从post中取出数据，赋值给登录表单对应字段
        if ($form->load(Yii::$app->getRequest()->post(), '') && $form->login()) {
            return Yii::$app->api->success($form->getUser()->loginInfo());
        }
        if ($form->hasErrors()) {
            return Yii::$app->api->error(parent::ERROR_CODE_FORM_FIELD_ERROR, $form->getFirstOneError());
        }
        return Yii::$app->api->error(parent::ERROR_CODE_FORM_ERROR, Yii::t('common', 'Account login failed.'));
    }
}
